﻿using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using QRCodePass.Application.Process;
using QRCodePass.Application.Process.Dtos;
using QRCodePass.Core.Models;
using QRCodePass.Core.Repositories;
using QRCodePass.Mvc.ViewModels.Process;

namespace QRCodePass.Mvc.Controllers
{
    public class ProcessController : Controller
    {
        private readonly IRepository<Process, int> _processRepository;
        private readonly IProcessService _processService;
        private readonly IRepository<Department, int> _departmentRepository;
        private readonly IRepository<Build, int> _buildRepository;

        public ProcessController(
            IRepository<Process, int> processRepository,
            IProcessService processService,
            IRepository<Department, int> departmentRepository,
            IRepository<Build, int> buildRepository)
        {
            _processRepository = processRepository;
            _processService = processService;
            _departmentRepository = departmentRepository;
            _buildRepository = buildRepository;
        }

        // 不填写 [HttpGet]默认为处理GET请求
        public async Task<ActionResult> Index(GetProcessInput input)
        {
            var models = await _processService.GetPaginatedResult(input);
            ProcessListModel listModel = new ProcessListModel()
            {
                Processes = models,
                AllProc = await _processRepository.GetAllListAsync()
            };
            return View(listModel);
        }

        #region 添加流程

        public ActionResult Create()
        {
            // var departDtos = DepartmentsDropDownList();
            int maxIndex = _processRepository.GetAll().OrderByDescending(x => x.Id).ToList()[0].Id;
            var buildDtos = BuildDropDownList();
            var procDtos = ProcDropDownList();
            var departDtos = DepartmentsDropDownList();
            ProcessCreateViewModel processCreateViewModel = new ProcessCreateViewModel
            {
                DepartmentList = departDtos,
                BuildList = buildDtos,
                ProcList = procDtos
            };
            ViewBag.Index = maxIndex + 1;
            return View(processCreateViewModel);
        }

        [HttpPost]
        public async Task<ActionResult> Create(ProcessCreateViewModel input)
        {
            if (ModelState.IsValid)
            {
                Process process = new Process
                {
                    Id = input.ProcessId,
                    ProcName = input.Title,
                    Description = input.Description,
                    BuildId = input.BuildId,
                    PreTask = input.PreTask
                };

                var departProc = new DepartProc()
                {
                    DepartmentId = input.DepartmentId,
                    ProcessId = input.ProcessId,
                };
                await _processRepository.InsertAsync(process);

                return RedirectToAction(nameof(Index));
            }
            return View();
        }

        #endregion 添加流程

        #region 编辑功能

        public IActionResult Edit(int? processId)
        {
            if (!processId.HasValue)
            {
                ViewBag.ErrorMessage = $"流程编号{processId}的信息不存在，请重试。";
                return View("NotFound");
            }

            var process = _processRepository.FirstOrDefault(a => a.Id == processId);

            if (process == null)
            {
                ViewBag.ErrorMessage = $"流程编号{processId}的信息不存在，请重试。";
                return View("NotFound");
            }
            //int maxIndex = _processRepository.GetAll().OrderByDescending(x => x.Id).ToList()[0].Id;
            var buildDtos = BuildDropDownList();
            var procDtos = ProcDropDownList();
            ProcessCreateViewModel processCreateViewModel = new ProcessCreateViewModel
            {
                ProcessId = process.Id,
                Description = process.Description,
                BuildId = process.BuildId,
                Title = process.ProcName,
                PreTask = process.PreTask,
                BuildList = buildDtos,
                ProcList = procDtos
            };
            return View(processCreateViewModel);
        }

        [HttpPost]
        public IActionResult Edit(ProcessEditViewModel input)
        {
            if (ModelState.IsValid)
            {
                var process = _processRepository.FirstOrDefault(a => a.Id == input.ProcessId);
                if (process != null)
                {
                    process.Description = input.Description;
                    process.ProcName = input.Title;
                    process.BuildId = input.BuildId;
                    process.PreTask = input.PreTask;
                    _processRepository.Update(process);
                    return RedirectToAction(nameof(Index));
                }
                else
                {
                    ViewBag.ErrorMessage = $"流程编号{input.ProcessId}的信息不存在，请重试。";
                    return View("NotFound");
                }
            }
            return View(input);
        }

        #endregion 编辑功能

        public async Task<ViewResult> Details(int processId)
        {
            ProcessDetailsModel processDetails = new ProcessDetailsModel()
            {
                 Process = await _processRepository.GetAll().Include(a => a.Departments).FirstOrDefaultAsync(a => a.Id == processId),
                 ProcessList = _processRepository.GetAll().ToList()
            };
            //判断流程信息是否存在
            if (processDetails.Process==null)
            {
                ViewBag.ErrorMessage = $"流程编号{processId}的信息不存在，请重试。";
                return View("NotFound");
            }
            return View(processDetails);
        }

        #region 删除功能

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            var model = await _processRepository.FirstOrDefaultAsync(a => a.Id == id);

            if (model == null)
            {
                ViewBag.ErrorMessage = $"流程编号{id}的信息不存在，请重试。";
                return View("NotFound");
            }

            // await _processAssignmentsRepository.DeleteAsync(a => a.Id == model.Id);

            await _processRepository.DeleteAsync(a => a.Id == id);
            return RedirectToAction(nameof(Index));
        }

        #endregion 删除功能

        #region 下拉列表

                /// <summary>
        /// 系部的下拉列表
        /// </summary>
        /// <param name="selectedDepartment"> </param>
        private SelectList DepartmentsDropDownList(object selectedDepartment = null)
        {
            var models = _departmentRepository.GetAll().OrderBy(a => a.Name).AsNoTracking().ToList();

            var departmentsDropDownList = new SelectList(models, "Id", "Name", selectedDepartment);

            return departmentsDropDownList;
        }

        /// <summary>
        /// 建筑的下拉列表
        /// </summary>
        /// <param name="selectedBuild"> </param>
        private SelectList BuildDropDownList(object selectedBuild = null)
        {
            var models = _buildRepository.GetAll().OrderBy(a => a.Id).AsNoTracking().ToList();

            var buildDropDownList = new SelectList(models, "Id", "Name", selectedBuild);

            return buildDropDownList;
        }

        /// <summary>
        /// 流程的下拉列表
        /// </summary>
        /// <param name="selectedProc"> </param>
        private SelectList ProcDropDownList(object selectedProc = null)
        {
            var models = _processRepository.GetAll().OrderBy(a => a.Id).AsNoTracking().ToList();

            var procDropDownList = new SelectList(models, "Id", "ProcName", selectedProc);

            return procDropDownList;
        }

        #endregion



    }
}